<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户管理 - 铁路管理系统</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="/admin/css/styles.css">
    <style>
        #app2 {
            display: flex;
            min-height: 100vh;
            width: 100%;
        }

        .status-active {
            color: #43a047;
            font-weight: 500;
        }

        .status-inactive {
            color: #e53935;
            font-weight: 500;
        }

        /* 添加停用按钮的棕色样式 */
        .btn-ban {
            background-color: #8B4513; /* 棕色 */
            color: white;
        }

        .modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: rgba(0, 0, 0, 0.5);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 1000;
        }

        .modal {
            background: white;
            border-radius: 8px;
            width: 90%;
            max-width: 600px;
            max-height: 90vh;
            overflow-y: auto;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
        }

        .modal-header {
            padding: 15px 20px;
            border-bottom: 1px solid #e0e0e0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .modal-body {
            padding: 20px;
        }

        .modal-footer {
            padding: 15px 20px;
            border-top: 1px solid #e0e0e0;
            display: flex;
            justify-content: flex-end;
            gap: 10px;
        }

        .close-btn {
            background: none;
            border: none;
            font-size: 1.5rem;
            cursor: pointer;
            color: #666;
            padding: 0;
            width: 30px;
            height: 30px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 4px;
        }

        .close-btn:hover {
            background-color: #f5f5f5;
        }

        .required {
            color: #e53935;
        }

        .no-data {
            text-align: center;
            padding: 40px 0;
            color: #999;
        }
    </style>
</head>
<body>

<div id="app2">
    <!-- 主内容区 -->
    <div class="main-content">


        <!-- 页面内容区域 -->
        <div id="page-content" style="padding: 0 20px;">
            <!-- 搜索和添加区域 -->
            <div class="card mb-4">
                <div class="card-header">
                    <h3 class="card-title">用户查询</h3>
                </div>
                <div class="card-body">
                    <form class="form-row" @submit.prevent="search">
                        <div class="form-group col-3">
                            <label for="username">用户名</label>
                            <input type="text" v-model="searchForm.username" class="form-control"
                                   placeholder="请输入用户名">
                        </div>
                        <div class="form-group col-3">
                            <label for="name">姓名</label>
                            <input type="text" v-model="searchForm.name" class="form-control"
                                   placeholder="请输入姓名">
                        </div>
                        <div class="form-group col-3">
                            <label for="roleId">角色</label>
                            <select v-model="searchForm.roleId" class="form-control">
                                <option value="">全部</option>
                                <option v-for="role in roleList" :key="role.roleId" :value="role.roleId">
                                    {{ role.roleName }}
                                </option>
                            </select>
                        </div>
                        <div class="form-group col-3">
                            <label for="status">状态</label>
                            <select v-model="searchForm.status" class="form-control">
                                <option value="">全部</option>
                                <option value="1">启用</option>
                                <option value="0">停用</option>
                            </select>
                        </div>
                        <div class="form-group col-12" style="margin-top: 20px;">
                            <button type="submit" class="btn btn-primary" style="margin-right: 10px;">
                                <i class="fas fa-search"></i> 搜索
                            </button>
                            <button type="button" class="btn btn-success" @click="openModal('添加用户')">
                                <i class="fas fa-plus"></i> 添加用户
                            </button>
                            <button type="button" class="btn btn-info" @click="exportUserList" style="margin-left: 10px;">
                                <i class="fas fa-file-export"></i> 导出用户列表
                            </button>
                        </div>
                    </form>
                </div>
            </div>

            <!-- 用户列表 -->
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">用户列表</h3>
                </div>
                <div class="card-body">
                    <div class="table-container">
                        <table>
                            <thead>
                            <tr>
                                <th>用户ID</th>
                                <th>用户名</th>
                                <th>姓名</th>
                                <th>性别</th>
                                <th>手机号码</th>
                                <th>邮箱</th>
                                <th>角色</th>
                                <th>状态</th>
                                <th>创建时间</th>
                                <th>操作</th>
                            </tr>
                            </thead>
                            <tbody>
                            <tr v-for="item in paginatedData" :key="item.userId">
                                <td>{{ item.userId }}</td>
                                <td>{{ item.username }}</td>
                                <td>{{ item.name }}</td>
                                <td>{{ item.sex === 1 ? '男' : '女' }}</td>
                                <td>{{ item.phone || '-' }}</td>
                                <td>{{ item.email || '-' }}</td>
                                <td>{{ item.role && item.role.roleName ? item.role.roleName : (item.roleName || '无角色') }}</td>
                                <td>
                                    <span v-if="item.status === 1" class="status-active">启用</span>
                                    <span v-else class="status-inactive">停用</span>
                                </td>
                                <td>{{ formatDateTime(item.createTime) }}</td>
                                <td>
                                    <div class="action-buttons">
                                        <button class="btn btn-sm btn-primary" @click="handleEdit(item)">
                                            <i class="fas fa-edit"></i> 编辑
                                        </button>
                                        <button class="btn btn-sm btn-danger" @click="handleDelete(item.userId)">
                                            <i class="fas fa-trash"></i> 删除
                                        </button>
                                        <button class="btn btn-sm" :class="item.status === 1 ? 'btn-ban' : 'btn-success'"
                                                @click="handleStatusChange(item.userId, item.status)">
                                            <i class="fas" :class="item.status === 1 ? 'fa-pause' : 'fa-play'"></i>
                                            {{ item.status === 1 ? '停用' : '启用' }}
                                        </button>
                                    </div>
                                </td>
                            </tr>
                            </tbody>
                        </table>
                        <!-- 无数据提示 -->
                        <div v-if="tableData.length === 0" class="no-data">
                            <p>暂无数据</p>
                        </div>
                    </div>

                    <!-- 分页控件 -->
                    <div class="pagination" v-if="totalItems > 0" style="margin-top: 20px; display: flex; justify-content: center; align-items: center;">
                        <button class="btn btn-sm" :disabled="currentPage === 1" @click="prevPage">&laquo;</button>

                        <span class="page-info" style="margin: 0 10px;">
                            第 {{ startIndex + 1 }}-{{ endIndex }} 条，共 {{ totalItems }} 条
                        </span>

                        <div class="page-numbers" style="display: flex; margin: 0 10px;">
                            <button v-for="page in pages" :key="page"
                                    class="btn btn-sm"
                                    :class="{ 'btn-primary': page === currentPage }"
                                    @click="goToPage(page)">
                                {{ page }}
                            </button>
                        </div>

                        <button class="btn btn-sm" :disabled="currentPage === totalPages" @click="nextPage">&raquo;
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 编辑模态框 -->
    <div v-if="isModalVisible" class="modal-overlay" @click.self="closeModal">
        <div class="modal">
            <div class="modal-header">
                <h3>{{ currentModalTitle }}</h3>
                <button class="close-btn" @click="closeModal">&times;</button>
            </div>
            <div class="modal-body">
                <form class="form-row">
                    <div class="form-group col-6">
                        <label for="editUsername">用户名 <span class="required">*</span></label>
                        <input type="text" class="form-control" id="editUsername" v-model="formData.username"
                               placeholder="请输入用户名" :disabled="!!formData.userId" required>
                    </div>
                    <div class="form-group col-6">
                        <label for="editName">姓名 <span class="required">*</span></label>
                        <input type="text" class="form-control" id="editName" v-model="formData.name"
                               placeholder="请输入姓名" required>
                    </div>
                    <div class="form-group col-6">
                        <label for="editPassword">密码</label>
                        <input type="text" class="form-control" id="editPassword" v-model="formData.password"
                               placeholder="请输入密码" @input="validatePassword">
                    </div>
                    <div class="form-group col-6">
                        <label for="editConfirmPassword">确认密码</label>
                        <input type="text" class="form-control" id="editConfirmPassword" v-model="formData.confirmPassword"
                               placeholder="请确认密码" @input="validatePassword">
                        <div v-if="passwordError" class="text-danger" style="font-size: 12px; margin-top: 5px;">
                            {{ passwordError }}
                        </div>
                    </div>
                    <div class="form-group col-6">
                        <label for="editRoleId">角色 <span class="required">*</span></label>
                        <select class="form-control" id="editRoleId" v-model="formData.roleId" required>
                            <option value="">请选择角色</option>
                            <option v-for="role in roleList" :key="role.roleId" :value="role.roleId">
                                {{ role.roleName }}
                            </option>
                        </select>
                    </div>
                    <div class="form-group col-6">
                        <label for="editStatus">状态</label>
                        <select class="form-control" id="editStatus" v-model="formData.status">
                            <option value="1">启用</option>
                            <option value="0">停用</option>
                        </select>
                    </div>
                    <div class="form-group col-6">
                        <label for="editSex">性别</label>
                        <select class="form-control" id="editSex" v-model="formData.sex">
                            <option value="1">男</option>
                            <option value="0">女</option>
                        </select>
                    </div>
                    <div class="form-group col-6">
                        <label for="editBirthday">出生日期</label>
                        <input type="date" class="form-control" id="editBirthday" v-model="formData.birthday">
                    </div>
                    <div class="form-group col-6">
                        <label for="editPhone">手机号码</label>
                        <input type="text" class="form-control" id="editPhone" v-model="formData.phone"
                               placeholder="请输入手机号码">
                    </div>
                    <div class="form-group col-6">
                        <label for="editEmail">邮箱</label>
                        <input type="email" class="form-control" id="editEmail" v-model="formData.email"
                               placeholder="请输入邮箱">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button class="btn btn-secondary" @click="closeModal">取消</button>
                <button class="btn btn-primary" @click="saveData">保存</button>
            </div>
        </div>
    </div>
</div>
<script src="/admin/js/auth.js"></script>
<script src="/admin/js/jquery-3.6.0.js"></script>
<script src="/admin/js/vue.js"></script>
<script src="/admin/js/load-navbar.js"></script>
<script src="/admin/js/user-info.js"></script>
<script src="/admin/js/axios.js"></script>
<script src="/admin/js/config.js"></script>

<script>
    new Vue({
        el: '#app2',
        data: {
            searchForm: {
                username: '',
                name: '',
                roleId: '',
                status: ''
            },
            tableData: [],
            roleList: [],
            formData: {
                userId: '',
                username: '',
                name: '',
                password: '',
                confirmPassword: '',
                roleId: '',
                status: 1,
                sex: 1,
                birthday: '',
                phone: '',
                email: ''
            },
            isModalVisible: false,
            currentModalTitle: '',
            userName: '',
            passwordError: '', // 用于存储密码校验错误信息

            // 分页相关数据
            currentPage: 1,
            pageSize: 8,
            totalItems: 0,
            useFrontendPagination: false
        },
        computed: {
            // 计算总页数
            totalPages() {
                return Math.ceil(this.totalItems / this.pageSize);
            },
            // 当前页显示的数据
            paginatedData() {
                return this.tableData;
            },
            // 显示的页码范围
            pages() {
                const pages = [];
                const maxVisiblePages = 5; // 最多显示5个页码
                let startPage = Math.max(1, this.currentPage - Math.floor(maxVisiblePages / 2));
                let endPage = Math.min(this.totalPages, startPage + maxVisiblePages - 1);
                if (endPage - startPage < maxVisiblePages - 1) {
                    startPage = Math.max(1, endPage - maxVisiblePages + 1);
                }
                for (let i = startPage; i <= endPage; i++) {
                    pages.push(i);
                }
                return pages;
            },
            // 计算当前页的起始索引
            startIndex() {
                return (this.currentPage - 1) * this.pageSize;
            },
            // 计算当前页的结束索引
            endIndex() {
                return Math.min(this.currentPage * this.pageSize, this.totalItems);
            }
        },
        methods: {
            search() {
                this.currentPage = 1; // 搜索时重置到第一页
                this.loadData();
            },
            openModal(title) {
                this.currentModalTitle = title;
                this.resetForm();
                this.isModalVisible = true;
            },
            closeModal() {
                this.isModalVisible = false;
                this.resetForm();
            },
            resetForm() {
                this.formData = {
                    userId: '',
                    username: '',
                    name: '',
                    password: '',
                    confirmPassword: '',
                    roleId: '',
                    status: 1,
                    sex: 1,
                    birthday: '',
                    phone: '',
                    email: ''
                };
            },
            handleEdit(item) {
                console.log('编辑用户数据:', item);

                // 重置表单
                this.resetForm();

                // 确保所有必要的属性都被正确赋值
                this.formData.userId = item.userId;
                this.formData.username = item.username;
                this.formData.name = item.name;

                // 在编辑用户时设置密码，以便在输入框中显示
                this.formData.password = item.password || '';
                this.formData.confirmPassword = item.password || '';

                // 处理角色ID - 保持与添加功能一致，使用字符串类型
                this.formData.roleId = '';
                if (item.role && item.role.roleId) {
                    this.formData.roleId = String(item.role.roleId);
                } else if (item.roleId) {
                    this.formData.roleId = String(item.roleId);
                }
                console.log('设置角色ID:', this.formData.roleId);

                // 处理状态 - 保持与添加功能一致，使用数值类型
                this.formData.status = typeof item.status !== 'undefined' ? Number(item.status) : 1;
                console.log('设置状态:', this.formData.status);

                // 处理新添加的字段
                this.formData.sex = typeof item.sex !== 'undefined' ? Number(item.sex) : 1;
                this.formData.birthday = item.birthday ? new Date(item.birthday).toISOString().split('T')[0] : '';
                this.formData.phone = item.phone || '';
                this.formData.email = item.email || '';

                // 如果角色列表为空，重新加载角色列表
                if (this.roleList.length === 0) {
                    this.loadRoleList().then(() => {
                        this.$nextTick(() => {
                            this.isModalVisible = true;
                            console.log('模态框显示，formData:', this.formData);
                        });
                    });
                } else {
                    // 强制更新Vue实例以确保变化被检测到
                    this.$nextTick(() => {
                        this.isModalVisible = true;
                        console.log('模态框显示，formData:', this.formData);
                    });
                }

                this.currentModalTitle = '编辑用户';
            },

            // 改造loadRoleList为返回Promise，以便在需要时等待角色加载完成
            loadRoleList() {
                return new Promise((resolve, reject) => {
                    axios.get('/admin/role_manage/getAllRoles')
                        .then(resp => {
                            if (resp.data.code === 200) {
                                this.roleList = resp.data.data || [];
                                console.log('角色列表加载完成:', this.roleList);
                                resolve(this.roleList);
                            } else {
                                alert('加载角色列表失败: ' + resp.message);
                                this.roleList = [];
                                reject(new Error(resp.message));
                            }
                        })
                        .catch(error => {
                            console.error('加载角色列表失败:', error);
                            alert('加载角色列表失败，请重试');
                            reject(error);
                        });
                });
            },
            handleDelete(userId) {
                if (confirm('确定要删除该用户吗？删除后数据将无法恢复！')) {
                    axios.delete(`/admin/user_manage/delete/${userId}`)
                        .then(resp => {
                            if (resp.data.code === 200) {
                                alert('删除成功');
                                this.loadData(); // 重新加载数据
                            } else {
                                alert('删除失败: ' + resp.data.message);
                            }
                        })
                        .catch(error => {
                            console.error('删除请求失败:', error);
                            alert('删除失败，请重试');
                        });
                }
            },
            handleStatusChange(userId, status) {
                const newStatus = status === 1 ? 0 : 1;
                const action = newStatus === 1 ? '启用' : '停用';

                if (confirm(`确定要${action}该用户吗？`)) {
                    axios.get('/admin/user_manage/changeStatus', { params: {newUserId:userId,myStatus: newStatus }})
                        .then(resp => {
                            if (resp.data.code === 200) {
                                alert(`${action}成功`);
                                this.loadData(); // 重新加载数据
                            } else {
                                alert(`${action}失败: ` + resp.data.message);
                            }
                        })
                        .catch(error => {
                            console.error(`${action}请求失败:`, error);
                            alert(`${action}失败，请重试`);
                        });
                }
            },
            validatePassword() {
                // 清空之前的错误信息
                this.passwordError = '';

                // 只有当两次输入都不为空时才进行校验
                if (this.formData.password && this.formData.confirmPassword) {
                    if (this.formData.password !== this.formData.confirmPassword) {
                        this.passwordError = '两次输入的密码不一致';
                    }
                }
            },
            saveData() {
                // 表单验证
                if (!this.formData.username) {
                    alert('请输入用户名');
                    return;
                }
                if (!this.formData.name) {
                    alert('请输入姓名');
                    return;
                }
                if (!this.formData.roleId) {
                    alert('请选择角色');
                    return;
                }

                // 密码验证逻辑
                if (!this.formData.userId) {
                    // 新增用户时，密码为必填
                    if (!this.formData.password) {
                        alert('请输入密码');
                        return;
                    }
                    if (this.formData.password !== this.formData.confirmPassword) {
                        alert('两次输入的密码不一致');
                        return;
                    }
                } else {
                    // 编辑用户时，如果输入了密码，则需要验证
                    if (this.formData.password !== '') {
                        if (this.formData.password !== this.formData.confirmPassword) {
                            alert('两次输入的密码不一致');
                            return;
                        }
                    }
                }

                const url = this.formData.userId ? '/admin/user_manage/update' : '/admin/user_manage/add';
                const submitData = { ...this.formData };

                // 编辑用户时，如果没有输入密码，则不提交密码字段
                if (this.formData.userId && this.formData.password === '') {
                    delete submitData.password;
                    delete submitData.confirmPassword;
                }

                axios.post(url, submitData)
                    .then(resp => {
                        if (resp.data.code === 200) {
                            alert(this.formData.userId ? '编辑成功' : '添加成功');
                            this.closeModal();
                            this.loadData(); // 重新加载数据
                        } else {
                            alert(this.formData.userId ? '编辑失败: ' : '添加失败: ' + resp.data.message);
                        }
                    })
                    .catch(error => {
                        console.error('保存请求失败:', error);
                        alert('操作失败，请重试');
                    });
            },
            // 分页方法
            prevPage() {
                if (this.currentPage > 1) {
                    this.currentPage--;
                    this.loadData();
                }
            },

            nextPage() {
                if (this.currentPage < this.totalPages) {
                    this.currentPage++;
                    this.loadData();
                }
            },

            goToPage(page) {
                this.currentPage = page;
                this.loadData();
            },

            loadData() {
                axios.get("/admin/user_manage/getList", {
                    params: {
                        page: this.currentPage,
                        pageSize: this.pageSize,
                        username: this.searchForm.username || null,
                        name: this.searchForm.name || null,
                        roleId: this.searchForm.roleId || null,
                        status: this.searchForm.status || null
                    }
                })
                    .then(resp => {
                        console.log('用户列表接口返回:', resp.data);
                        if (resp.data && resp.data.code === 200) {
                            const data = resp.data.data;
                            if (Array.isArray(data)) {
                                // 后端直接返回数组
                                this.tableData = data;
                                this.totalItems = data.length;
                            } else if (data && Array.isArray(data.list)) {
                                // 后端返回分页对象 { list, total }
                                this.tableData = data.list;
                                this.totalItems = Number(data.total) || data.list.length;
                            } else if (data && Array.isArray(data.rows)) {
                                // 兼容另一种命名 { rows, total }
                                this.tableData = data.rows;
                                this.totalItems = Number(data.total) || data.rows.length;
                            } else {
                                console.warn('未知数据结构，无法解析为列表:', data);
                                this.tableData = [];
                                this.totalItems = 0;
                            }
                        } else {
                            alert("加载数据失败: " + (resp.data ? resp.data.message : '未知错误'));
                            this.tableData = [];
                            this.totalItems = 0;
                        }
                    })
                    .catch(error => {
                        console.error('加载数据失败:', error);
                        alert('加载数据失败，请重试');
                    });
            },

            loadRoleList() {
                axios.get("/admin/role_manage/getAllRoles")
                    .then(resp => {
                        if (resp.data.code === 200) {
                            this.roleList = resp.data.data || [];
                        } else {
                            alert("加载角色列表失败: " + resp.message);
                            this.roleList = [];
                        }
                    })
                    .catch(error => {
                        console.error('加载角色列表失败:', error);
                    });
            },

            formatDateTime(dateTime) {
                if (!dateTime) return '';
                const date = new Date(dateTime);
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                const hours = String(date.getHours()).padStart(2, '0');
                const minutes = String(date.getMinutes()).padStart(2, '0');
                const seconds = String(date.getSeconds()).padStart(2, '0');
                return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
            },
            
            // 导出用户列表
            exportUserList() {
                // 显示加载状态
                this.exportLoading = true;
                alert('正在导出用户列表，请稍候...'); // 使用原生alert替代this.$message
                
                // 构造导出参数，使用当前的搜索条件
                const exportParams = {
                    username: this.searchForm.username || '',
                    name: this.searchForm.name || '',
                    roleId: this.searchForm.roleId || '',
                    status: this.searchForm.status || ''
                };
                
                // 使用axios发送导出请求
                axios.post('/admin/user_manage/export', exportParams, {
                    responseType: 'blob',
                    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
                })
                .then(response => {
                    this.exportLoading = false;
                    // 移除this.$message.closeAll()调用
                     
                    // 解析文件名
                    const contentDisposition = response.headers['content-disposition'];
                    let fileName = '用户列表.xls';
                    if (contentDisposition) {
                        const filenameMatch = contentDisposition.match(/filename=(.*)/);
                        if (filenameMatch && filenameMatch[1]) {
                            fileName = decodeURIComponent(filenameMatch[1]);
                        }
                    }
                     
                    // 创建下载链接
                    const url = window.URL.createObjectURL(new Blob([response.data]));
                    const link = document.createElement('a');
                    link.href = url;
                    link.download = fileName;
                    document.body.appendChild(link);
                    link.click();
                     
                    // 清理资源
                    setTimeout(() => {
                        window.URL.revokeObjectURL(url);
                        document.body.removeChild(link);
                    }, 100);
                     
                    alert('用户列表导出成功'); // 使用原生alert替代this.$message.success
                })
                .catch(error => {
                    this.exportLoading = false;
                    this.$message.closeAll();
                     
                    // 错误处理
                    if (error.response && error.response.status === 500) {
                        alert('服务器错误，导出失败'); // 使用原生alert替代this.$message.error
                    } else if (error.response && error.response.data) {
                        alert('导出失败: ' + error.response.data); // 使用原生alert替代this.$message.error
                    } else {
                        alert('网络错误，导出失败'); // 使用原生alert替代this.$message.error
                    }
                    console.error('导出错误:', error);
                });
            }
        },
        mounted() {
            // 加载用户列表
            this.loadData();
            // 加载角色列表
            this.loadRoleList();
            // 设置当前页面标识
            sessionStorage.setItem('currentPage', 'user_manage.html');
        }
    });
</script>
</body>
</html>
